package com.zcx.base.log.filter;



import com.zcx.base.log.local.LogThreadLocal;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;
import java.util.UUID;

/**
 * 增加输出日志traceRootId
 */
@Component
public class LogFilter implements Filter {

    private static final String UNIQUE_ID = "traceId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        MDC.put(UNIQUE_ID, LogThreadLocal.getTraceId());
        try {
            chain.doFilter(request, response);
        } finally {
            LogThreadLocal.getLog().remove();
            MDC.remove(UNIQUE_ID);
        }
    }

    private boolean insertMDC() {
        UUID uuid = UUID.randomUUID();
        String uniqueId = UNIQUE_ID +"-"+ uuid.toString().replace("-", "");
        MDC.put(UNIQUE_ID, uniqueId);
        return true;
    }

    @Override
    public void destroy() {

    }

}
